import Message from 'tdesign-miniprogram/message/index';

Page({
  data: {
    // 识别的文字内容
    recognizedText: '',
    // 图片路径
    imagePath: '',
    // 是否正在识别
    isRecognizing: false,
    // 识别结果
    recognitionResult: null
  },

  onLoad() {
    // 页面加载时的初始化
  },

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack();
  },

  /**
   * 拍照识别
   */
  takePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({ imagePath: tempFilePath });
        this.recognizeText(tempFilePath);
      },
      fail: (error) => {
        console.error('拍照失败:', error);
        Message.error({
          context: this,
          content: '拍照失败，请重试',
          duration: 2000
        });
      }
    });
  },

  /**
   * 从相册选择
   */
  chooseFromAlbum() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.setData({ imagePath: tempFilePath });
        this.recognizeText(tempFilePath);
      },
      fail: (error) => {
        console.error('选择图片失败:', error);
        Message.error({
          context: this,
          content: '选择图片失败，请重试',
          duration: 2000
        });
      }
    });
  },

  /**
   * 识别文字
   */
  async recognizeText(imagePath) {
    this.setData({ isRecognizing: true });

    try {
      // 这里应该调用真实的 OCR API
      // 目前使用模拟数据
      await this.mockOCRRecognition(imagePath);
      
      Message.success({
        context: this,
        content: '识别成功',
        duration: 1500
      });
    } catch (error) {
      console.error('文字识别失败:', error);
      Message.error({
        context: this,
        content: '识别失败，请重试',
        duration: 2000
      });
    } finally {
      this.setData({ isRecognizing: false });
    }
  },

  /**
   * 模拟 OCR 识别
   */
  async mockOCRRecognition(imagePath) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockText = `读书破万卷，下笔如有神。
        
这句话出自唐代诗人杜甫的《奉赠韦左丞丈二十二韵》，意思是说：读的书多了，写文章时就会文思泉涌，如有神助。

这句话告诉我们，多读书是提高写作能力的重要途径。通过大量阅读，我们可以积累丰富的词汇、优美的句式和深刻的思想，这些都是写作的基础。`;

        this.setData({
          recognizedText: mockText,
          recognitionResult: {
            text: mockText,
            confidence: 0.95,
            language: 'zh-CN'
          }
        });
        resolve();
      }, 2000);
    });
  },

  /**
   * 编辑识别结果
   */
  editText(e) {
    const text = e.detail.value;
    this.setData({ recognizedText: text });
  },

  /**
   * 复制识别结果
   */
  copyText() {
    const { recognizedText } = this.data;
    if (!recognizedText) {
      Message.warning({
        context: this,
        content: '没有可复制的内容',
        duration: 2000
      });
      return;
    }

    wx.setClipboardData({
      data: recognizedText,
      success: () => {
        Message.success({
          context: this,
          content: '已复制到剪贴板',
          duration: 1500
        });
      },
      fail: () => {
        Message.error({
          context: this,
          content: '复制失败',
          duration: 2000
        });
      }
    });
  },

  /**
   * 发布书摘
   */
  publishPost() {
    const { recognizedText } = this.data;
    if (!recognizedText.trim()) {
      Message.warning({
        context: this,
        content: '请先识别或输入文字内容',
        duration: 2000
      });
      return;
    }

    // 跳转到发布页面，并传递识别的内容
    wx.navigateTo({
      url: `/pages/release/index?content=${encodeURIComponent(recognizedText)}`
    });
  },

  /**
   * 重新识别
   */
  reRecognize() {
    this.setData({
      recognizedText: '',
      recognitionResult: null
    });
  }
});
